//
//  LQComposeTextView.swift
//  Weibo
//
//  Created by ios on 16/8/16.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

class LQComposeTextView: UITextView {
    //设置占位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "东京不太热"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor =  UIColor.lightGrayColor()
        label.numberOfLines = 0
        return label
    }()
    
     //  提供外界设置占位文字的属性
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
            
        }
    }

      //   重写font
    override var font: UIFont? {
        didSet{
            if font != nil {
              placeHolderLabel.font = font
            }
        }
    }
    
    //  重写text
    override var text: String? {
        didSet {
            //  根据文本内容显示占位label
            placeHolderLabel.hidden = hasText()
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //添加控件 设置约束
    private func setupUI(){
        //  监听文字改变的通知
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    addSubview(placeHolderLabel)
    //  使用系统约束,防止第三方的限制
    
    placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
    
    addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    
    }
    
     //  MARK: --监听文字改变的通知
    @objc func textChange(){
        //  根据是否有值判断是否显示占位label
        placeHolderLabel.hidden = hasText()
    }
    
    //  给子控件设置约束
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置x,y坐标
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 7
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }

}








